import regeneratorRuntime from '../../lib/runtime/runtime';
import { request } from '../../request/index.js'
Page({
  data: {
    userAddress: {},
    cart: [],
    //商品总数量
    totalPrice: 0,
    // 商品总价格
    totalNum: 0,
    address:''
  },
  onShow() {
    const userAddress = wx.getStorageSync("res")
    // 获取缓存中的购物车数据
    let cart = wx.getStorageSync("cart") || []
    cart = cart.filter(v => v.checked)
    this.setData({userAddress})
    // 收货地址
    const address = userAddress.provinceName+userAddress.cityName+userAddress.countyName+userAddress.detailInfo
    // 商品总价格
    let totalPrice = 0
    // 商品总数量
    let totalNum = 0
    cart.forEach((v) => {
        totalPrice += v.num * v.goods_price
        totalNum += v.num
    })
    this.setData({
      cart,
      totalPrice,
      totalNum,
      userAddress,
      address
    })
  },
  async handelPrderPay(){
    const token = wx.getStorageSync("token")
    if(!token){
      wx.navigateTo({
        url: '/pages/auth/index',
      });
      return 
    }
    // 请求头
    const header = {Authorization:token}
    //请求体
    const order_price = this.data.totalPrice
    const consignee_addr = this.data.address
    let goods = []
    const cart = this.data.cart
    cart.forEach(v=>goods.push({
      goods_id: v.goods_id,
      goods_number: v.num,
      goods_price: v.goods_price
    }))
    const list = {
      order_price,consignee_addr,goods
    }
    // 创建订单 获取订单编号
    const {order_number} = await request({url:"/my/orders/create",method:'POST',data:list,header})
    //获取支付参数
    const {pay} = await request({url:"/my/orders/req_unifiedorder",method:'POST',data:{order_number},header})
    wx.requestPayment({
      timeStamp: pay.timeStamp,
      nonceStr: pay.nonceStr,
      package: pay.package,
      signType: pay.signType,
      paySign: pay.paySign,
      fail (res) {
        wx.showToast({
          title: '暂无支付功能!',
          icon: 'error',
          duration: 2000
        })
      }
    })
    // const res = await request({url:"/my/orders/chkOrder",method:'POST',data:{order_number},header})
    // console.log(res)
  }
})